package com.smartsofa.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.smartsofa.R;
import com.smartsofa.adapter.TopicListAdapter;
import com.smartsofa.entity.Page;
import com.smartsofa.main.PublishTopic;
import com.smartsofa.util.MyUtils;

public class CircleFragment extends Fragment {
	private FragmentActivity mActivity;
	private View mParent;	
	private ProgressDialog mDialog;	
	
	private String url;
	private Boolean flag;
	public int currpage=1;

	protected int topicId;
	
	private JSONObject json;
	private JSONArray jsonarr;
	private List<Map<String, Object>> mData; 
	private List<Map<String, Object>> mData2=new ArrayList<Map<String,Object>>(); 
	private TopicListAdapter adapter;
	private PullToRefreshListView pullToRefresh;  //实现下拉刷新与上拉加载的ListView		
	private LinearLayout lay_newtopic;
	//定义网络连接超时判定变量
	private boolean network_timeout=false;
	
	Page page=new Page();
	Intent intent;

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view=inflater.inflate(R.layout.fragment_circle, container,false);
		return view;
	}
	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mActivity = getActivity();  
	    mParent = getView();
	    //显示加载对话框
	    mDialog = new ProgressDialog(mActivity);
		mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mDialog.setMessage("加载中，请稍后...");
		mDialog.show();		
	    
	  //初始化控件
		lay_newtopic=(LinearLayout) mActivity.findViewById(R.id.lay_newtopic);
		lay_newtopic.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				intent=new Intent().setClass(mActivity, PublishTopic.class);
				startActivity(intent);
			}
		});
	    pullToRefresh = (PullToRefreshListView)mActivity.findViewById(R.id.pullToRefresh);     
        pullToRefresh.setMode(Mode.BOTH);
        init(); 
        pullToRefresh.setOnRefreshListener(new OnRefreshListener2<ListView>(){  
       	 public void onPullDownToRefresh(  
                    PullToRefreshBase<ListView> refreshView) {  
                // TODO Auto-generated method stub                                  
			    new GetDataTaskDown().execute(); 
            }  
              
            public void onPullUpToRefresh(  
                    PullToRefreshBase<ListView> refreshView) {  
                // TODO Auto-generated method stub  
           	 new GetDataTaskUp().execute();           	   
            }
       });				
	    loadTopicData();  
	}

	private void init(){    
        ILoadingLayout startLabels = pullToRefresh    
                .getLoadingLayoutProxy(true, false);    
        startLabels.setPullLabel("下拉刷新...");// 刚下拉时，显示的提示    
        startLabels.setRefreshingLabel("正在载入...");// 刷新时    
        startLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示    
    
        ILoadingLayout endLabels = pullToRefresh.getLoadingLayoutProxy(    
                false, true);    
        endLabels.setPullLabel("上拉刷新...");// 刚下拉时，显示的提示    
        endLabels.setRefreshingLabel("正在载入...");// 刷新时    
        endLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示    
    }
	
	/**
	 * 加载帖子列表数据
	 */
	private void loadTopicData() {
		// TODO Auto-generated method stub    
		Thread contentdata = new Thread(new loadTopicNet());
		contentdata.start();
	}
	/**
	 * 获取帖子列表数据
	 * @author YuHuan
	 *
	 */
	class loadTopicNet implements Runnable{		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {		
				url=MyUtils.getUrl()+"topic_getTopicList?currpage="+1+"&pagesize="+page.getPagesize();
				Log.i("url", url);
				HttpGet request = new HttpGet(url);																
				BasicHttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
			    HttpClient httpClient = new DefaultHttpClient(httpParams);
	            HttpResponse httpResponse = httpClient.execute(request);							       
		       	
		      if (httpResponse.getStatusLine().getStatusCode() == 200) {
		    	network_timeout=true;
		        String jsonString = EntityUtils.toString(httpResponse.getEntity());
		        json = new JSONObject(jsonString);
		        flag=(Boolean) json.get("success");			        				      		       
		      }
		      }catch (Exception e) {
		        	 e.printStackTrace();
		      }
			Message msg = content_handler.obtainMessage();
			if(network_timeout){
				if (flag) {				
					msg.what = 1;									
				}else{
					msg.what = 2;			
				}
			}			
			else{
				msg.what = 3;						
			}
			content_handler.sendMessage(msg);
		}
	}
	Handler content_handler = new Handler() {
		public void handleMessage(Message msg) {			
			switch (msg.what) {		
			case 1:	
				mDialog.cancel();
				try {
					page.setCurrpage(1);
					mData=getData(json);
				    adapter = new TopicListAdapter(mActivity.getApplicationContext(),mData);
			        pullToRefresh.setAdapter(adapter);
//			        pullToRefresh.onRefreshComplete(); //结束刷新
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				break;
			case 2:
				mDialog.cancel();
				Toast.makeText(mActivity.getApplicationContext(), "数据加载失败，请稍后重试！", Toast.LENGTH_SHORT).show();
				break;
			case 3:
				mDialog.cancel();
				Toast.makeText(mActivity.getApplicationContext(), "网络连接超时！", Toast.LENGTH_SHORT).show();
				break;
			}
		}		
	};
	

	
	   private class GetDataTaskDown extends AsyncTask<Void, Void, Void> {  
		   
	       //后台处理部分  
	       protected Void doInBackground(Void... params) {  
	           // Simulates a background job.  
	       	   loadTopicData(); 
	           return null;
	       }
	 
	       //这里是对刷新的响应，可以利用addFirst（）和addLast()函数将新加的内容加到LISTView中  
	       //根据AsyncTask的原理，onPostExecute里的result的值就是doInBackground()的返回值  
	       protected void onPostExecute(Void result) {  
	           //在头部增加新添内容  
//	           mListItems.addFirst(result);  	             
	           //通知程序数据集已经改变，如果不做通知，那么将不会刷新mListItems的集合  
	           adapter.notifyDataSetChanged();  
	           // Call onRefreshComplete when the list has been refreshed.  
	           pullToRefresh.onRefreshComplete();  	 
	           super.onPostExecute(result);  
	       }
	   }
	   
	   private class GetDataTaskUp extends AsyncTask<Void, Void, List<Map<String, Object>>> {  
		   
	       //后台处理部分  
	       protected List<Map<String, Object>> doInBackground(Void... params) {  
	           // Simulates a background job.  
	    	   try {
					url=MyUtils.getUrl()+"topic_getTopicList?currpage="+page.getCurrpage()+"&pagesize="+page.getPagesize();
					Log.i("url", url);
					HttpGet request = new HttpGet(url);																
					BasicHttpParams httpParams = new BasicHttpParams();
					HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
				    HttpClient httpClient = new DefaultHttpClient(httpParams);
		            HttpResponse httpResponse = httpClient.execute(request);							       
			       	
			      if (httpResponse.getStatusLine().getStatusCode() == 200) {
			    	network_timeout=true;
			        String jsonString = EntityUtils.toString(httpResponse.getEntity());
			        json = new JSONObject(jsonString);
			        flag=(Boolean) json.get("success");
			        Message msg = content_handler.obtainMessage();
					if(network_timeout){
						mData2.clear();
						if (flag) {				
							msg.what = 1;
							page.setCurrpage(page.getCurrpage());
							mData2=getData(json);
						}else{
							msg.what = 2;			
						}
					}			
					else{
						msg.what = 3;						
					}
					pulltorefresh_handler.sendMessage(msg);
					}			      
			      }catch (Exception e) {
			        	 e.printStackTrace();
			      }								
	           return mData2;
	       }
	 
	       //这里是对刷新的响应，可以利用addFirst（）和addLast()函数将新加的内容加到LISTView中  
	       //根据AsyncTask的原理，onPostExecute里的result的值就是doInBackground()的返回值  
	       protected void onPostExecute(List<Map<String, Object>> result) { 
	    	   if(mData2.size()>0){
	    		   //在头部增加新添内容  
		           mData.addAll(result);  
		           //通知程序数据集已经改变，如果不做通知，那么将不会刷新mListItems的集合  
		           adapter.notifyDataSetChanged();  
		           // Call onRefreshComplete when the list has been refreshed.  		           
	    	   }
	    	   pullToRefresh.onRefreshComplete();
	           super.onPostExecute(result);  
	       }
	   }
	   
	   
		Handler pulltorefresh_handler = new Handler() {
			public void handleMessage(Message msg) {			
				switch (msg.what) {		
				case 1:	
					if(mData2.size()==0){
						Toast.makeText(mActivity, "没有更多数据了！", Toast.LENGTH_SHORT).show();
					}
					break;
				case 2:
					Toast.makeText(mActivity, "没有更多数据了！", Toast.LENGTH_SHORT).show();
					break;
				case 3:
					Toast.makeText(mActivity, "网络连接超时！", Toast.LENGTH_SHORT).show();
					break;
				}
			}		
		};
	
	
	/**
	 * 获取数据
	 * @throws JSONException 
	 */
	private List<Map<String, Object>> getData(JSONObject json) throws JSONException{
		jsonarr=json.getJSONArray("obj");	
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	    for(int i=0;i<jsonarr.length();i++)  
           {  			    	   
               HashMap<String, Object> map = new HashMap<String, Object>();  
               if(jsonarr.getJSONObject(i).has("userImg")){
            	   map.put("userImg", jsonarr.getJSONObject(i).get("userImg"));
               }			  
			   map.put("userName", jsonarr.getJSONObject(i).get("userName")); 
               map.put("publicTime", jsonarr.getJSONObject(i).get("publicTime"));
               map.put("topicContent", jsonarr.getJSONObject(i).get("topicContent"));
               map.put("praiseNum", jsonarr.getJSONObject(i).get("praiseNum"));
               map.put("commentNum", jsonarr.getJSONObject(i).get("commentNum"));
               map.put("topicId", jsonarr.getJSONObject(i).get("topicId"));
               map.put("userId", jsonarr.getJSONObject(i).get("userId"));	
               list.add(map);
           }
	    return list;
	}
			
}

